import {PacMan} from "./PacMan"

export class Game{
    constructor(domID,option){
        this.run = this.run.bind(this)
        this.initial = this.initial.bind(this)
        this.drawPac = this.drawPac.bind(this)
        this.clear = this.clear.bind(this)
        
        let {frame=50} = option
        this.frame = frame

        this.dom = document.getElementById(domID)
        this.can = this.dom.getContext("2d")


        this.pacMan = new PacMan({dom:this.dom})

        this.run()

        document.addEventListener("keydown",event=>{
            event = event || window.event

            let {keyCode} = event

            switch(keyCode){
                case 37:
                    this.pacMan.setDir("left")
                    break
                case 38:
                    this.pacMan.setDir("up")
                    break
                case 39:
                    this.pacMan.setDir("right")
                    break
                case 40:
                    this.pacMan.setDir("down")
                    break

            }
        })
    }
    
    run(){
        let {initial,clear} = this

        initial()
        clear()
        
        this.drawPac()
        this.pacMan.nextMouth()
        this.pacMan.nextLocation()

        setTimeout(()=>{
            this.run()
        },this.frame)

    }

    clear(){
        let {can,dom} = this
        
        can.clearRect(0,0,dom.width,dom.height)
    }

    drawPac(){
        let {can,initial,pacMan} = this
        

        initial()
        let {x,y,size,color,mStatus,mLevel,cMLevel,direction} = pacMan

        let start = 0.25*Math.PI / mLevel * cMLevel
        let end = -0.25*Math.PI / mLevel * cMLevel + 2*Math.PI

        switch(direction){
            case "left":
                start += Math.PI
                end += Math.PI
                break
            case "down":
                start += 0.5*Math.PI
                end += 0.5*Math.PI
                break
            case "up":
                start -= 0.5*Math.PI
                end -= 0.5*Math.PI
                break
        }

        can.fillStyle = color
        can.moveTo(x,y)
        can.arc(x,y,size,start,end)
        can.closePath()
        can.fill()

    }

    initial(){
        let {can} = this

        can.restore()
        can.save()
        can.beginPath()
    }
}